package cn.virens.web.components.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.alibaba.fastjson.JSONObject;

public class WebSocketHandler extends TextWebSocketHandler {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		logger.debug("连接成功:{}", session.getRemoteAddress());
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		logger.debug("收到消息:{}", message.getPayload());
		// 获取到消息
		JSONObject json = JSONObject.parseObject(message.getPayload());
		String account = json.getString("account");
		String time = json.getString("time");
		String text = json.getString("message");
		// 返回消息
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		logger.debug("连接关闭");
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		super.handleTransportError(session, exception);
		logger.debug("连接异常", exception);
	}

}